import React, { useState, useEffect, useRef } from 'react';
import { Form, Button, Checkbox, Input, Skeleton, App } from 'antd';
import { MobileOutlined, LockOutlined, CommentOutlined } from '@ant-design/icons';
import loadable from '@loadable/component';
import { useHistory } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';

import { isRegMobile } from '@/utils';
import { loginPwd } from '@/service/base';
import { setStore } from '@/reducers/common';


export default (props) => {
    const initState = () => ({
        submitting: false,
    });
    const [state, setState] = useState(initState);
    const { message } = App.useApp();
    const {onOk, onCancel} = props;
    const [form] = Form.useForm();
    const dispatch = useDispatch();

    // 工具函数
    const loading = (flag=true) => setState(o => ({...o, submitting: flag}));

    // 提交表单
    const onFinish = values => {
        message.destroy();
        loading();

        loginPwd({...values, password: md5(values.password)}).then(res => {
            if(OK_CODE !== res?.code) {
                loading(false);
                return message.warning(res?.message);
            }

            const {token, user: userInfo} = res?.data || {};

            // 设置token等信息后再跳转
            localStorage.setItem('accessToken', token);
            localStorage.removeItem('inviter_code');
            dispatch(setStore({userInfo}));

            onOk();
        }).catch(e => {
            loading(false);
            message.error(e?.message);
        });
    };

    return (
        <Form
            form={form}
            onFinish={onFinish}
            size="large"
        >
            <Form.Item
                name="phone"
                rules={[
                    { required: true, message: '请输入手机号' },
                    { validator: (_, value) => {
                        if(value && !isRegMobile(value)) return Promise.reject(`请输入正确的手机号`);
                        return Promise.resolve();
                    }},
                ]}
            >
                <Input
                    type="tel"
                    prefix={<MobileOutlined className="site-form-item-icon" />}
                    placeholder="手机号"
                />
            </Form.Item>
            <Form.Item
                name="password"
                rules={[
                    { required: true, message: '请输入验证码' }
                ]}
            >
                <Input.Password
                    prefix={<LockOutlined />}
                    placeholder="密码"
                />
            </Form.Item>

            <Button
                loading={state.submitting}
                type="primary"
                htmlType="submit"
                block
            >
                登录
            </Button>
        </Form>
    );
};